package day02;

import exception.DataAccessException;
import util.JdbcUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/remove")
public class RemoveEmpServlet extends HttpServlet {


    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("RemoveEmpServlet.service()");

        Integer id = Integer.parseInt(request.getParameter("id"));

        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = JdbcUtil.getConnection();

            con.setAutoCommit(false);

            String sql = new StringBuffer()
                    .append("delete from t_emp ")
                    .append("where id=? ")
                    .toString();

            ps = con.prepareStatement(sql);

            ps.setInt(1, id);

            ps.executeUpdate();

            con.commit();

        } catch (Exception e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
            throw new DataAccessException("数据访问失败", e);
        } finally {
            JdbcUtil.close(con, ps, rs);
        }

        response.sendRedirect(request.getContextPath() + "/list");

    }
}
